package com.xavier.dong.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author XavierDong
 **/
public class NIOFileChannel03 {

    public static void main(String[] args) {


        try (FileInputStream fileInputStream = new FileInputStream("1.txt");
             FileOutputStream fileOutputStream=new FileOutputStream("2.txt")) {

            FileChannel fileChannel01 = fileInputStream.getChannel();

            FileChannel fileChannel02 = fileOutputStream.getChannel();


            // 创建一个 ByteBuffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(512);

            // 循环读取
            while (true) {

                // 这边有一个重要的操作，不要忘了
                // 清空 Buffer
                byteBuffer.clear();

                int read = fileChannel01.read(byteBuffer);

                if (read==-1)
                    // 表示读完
                    break;
                // 将 ByteBuffer 中的 数据 写入到 fileChannel02------->2.txt
                byteBuffer.flip();
                fileChannel02.write(byteBuffer);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
